/*
 * Copyright @ 2024 weili23
 * com.hmdp.utils 17:57
 * All right reserved.
 */

package com.hmdp.utils;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.BooleanUtil;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.concurrent.TimeUnit;

/**
 * @desc: redis锁
 * @author: weili23
 * @createTime: 2024/3/21 17:57
 * @version: v1.0
 */
public class RedisLock implements ILock{
    private String keyName;
    private StringRedisTemplate stringRedisTemplate;

    public RedisLock(String keyName, StringRedisTemplate stringRedisTemplate) {
        this.keyName = keyName;
        this.stringRedisTemplate = stringRedisTemplate;
    }

    private static final String UUID_PREFIX = UUID.randomUUID().toString(true)+"-";
    private static final String KEY_PREFIX="lock:";
    @Override
    public boolean tryLock(Long time) {
        String threadId =UUID_PREFIX+ Thread.currentThread().getId();
        Boolean absent = stringRedisTemplate.opsForValue().setIfAbsent(KEY_PREFIX + keyName, threadId, time, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(absent);
    }

    @Override
    public void unlock() {
        // 获取线程id
        String threadId =UUID_PREFIX+ Thread.currentThread().getId();
        //优化释放自己的锁
        String keyValue = stringRedisTemplate.opsForValue().get(KEY_PREFIX + keyName);
        if(threadId.equals(keyValue)){
            stringRedisTemplate.delete(KEY_PREFIX+keyName);
        }


    }
}
